package org.example;

import cn.dev33.satoken.config.SaSignConfig;
import cn.dev33.satoken.secure.SaBase64Util;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.sign.SaSignTemplate;
import cn.hutool.core.lang.Console;
import cn.hutool.core.net.Ipv4Util;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;

import java.net.HttpCookie;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

public class SignatureMain {

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        for (int i = 0; i < 2; i++) {
            String url = "http://127.0.0.1:8080/api1/hello";
            Map<String, Object> paramMap = new LinkedHashMap<>();
            paramMap.put("userId", 10001);
            paramMap.put("money", "asdasdad");
            paramMap.put("con", "啊哈那1啥哈问问");
            String str = url + "?" + sign(paramMap);
            Console.log(str);
            HashMap<String, Object> post = new HashMap<>();
            post.put("p1", encrypt("9999987979" + UUID.randomUUID()));
            post.put("p2", encrypt("qweqwe" + UUID.randomUUID()));
            post.put("p3", encrypt("啊哈那11啥哈问问" + UUID.randomUUID()));

            HttpCookie cookie = new HttpCookie("user", String.valueOf(i));
            try (HttpResponse response = HttpUtil.createPost(str).body(JSONUtil.toJsonStr(post)).cookie(cookie).execute()) {
//                Console.log(response.body());
                Console.log(decode(response.body()));
            }
        }
        Console.log(System.currentTimeMillis() - start);
    }

    public static String sign(Map<String, Object> paramMap) {
        SaSignConfig config = new SaSignConfig();
        config.setSecretKey("485hIn359#)Pty391");
        SaSignTemplate saSignTemplate = new SaSignTemplate(config);
        Map<String, Object> ps = saSignTemplate.addSignParams(paramMap);
        for (String key : ps.keySet()) {
            if ("sign".equals(key) || "nonce".equals(key) || "timestamp".equals(key)) {
                continue;
            }
            ps.put(key, encrypt(ps.get(key)));
        }
        return saSignTemplate.joinParams(ps);
    }

    public static String encrypt(Object str) {
        String secret = "851xWg959#&LTW238322zPo165#^mrm274";
        return SaBase64Util.encode(SaSecureUtil.aesEncrypt(secret, String.valueOf(str)));
    }

    public static String decode(Object str) {
        String secret = "851xWg959#&LTW238322zPo165#^mrm274";
        return SaSecureUtil.aesDecrypt(secret, SaBase64Util.decode(String.valueOf(str)));
    }
}
